<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="110px">
      <el-form-item label="订单类型" prop="orderContent">
        <el-select v-model="formData.orderContent" placeholder="请选择订单类型">
          <el-option v-for="item in getIntDictOptions(DICT_TYPE.ORDER_CONTENT)" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="formData.projectName" placeholder="请输入项目名称" />
      </el-form-item>
      <el-form-item label="交付物" prop="deliverables">
        <el-input v-model.trim="formData.deliverables" placeholder="请输入交付物类型" />
      </el-form-item>
      <el-form-item label="支付方式" prop="payMethod">
        <el-select v-model="formData.payMethod" placeholder="请选择支付方式">
          <el-option v-for="item in getIntDictOptions(DICT_TYPE.PAY_METHOD)" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额" prop="quote">
        <el-input-number v-model="formData.quote" :min="0" :max="100000000" :precision="0" style="width: 36%" />
        &nbsp;&nbsp;<el-tooltip content="订单金额需为整数，小数位会自动四舍五入" placement="top" effect="light" style="margin-left: 2%;">
          <el-icon>
            <InfoFilled />
          </el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="期望交付时间" prop="expectedDate">
        <el-date-picker v-model="formData.expectedDate" :disabled-date="disabledDate" type="date" placeholder="请选择交付时间"
          format="YYYY-MM-DD" value-format="x" />
      </el-form-item>
      <el-form-item label="报价单" prop="file">
        <el-upload ref="uploadRef" v-model:file-list="file" :action="importUrl" :disabled="formType === 'view'"
          :headers="uploadHeaders" :limit="1" :on-success="submitFormSuccess" :on-change="handleChange"
          :on-remove="handleRemove" :on-error="submitFormError" :on-exceed="handleExceed" :on-preview="handlePreview"
          :before-upload="beforeUpload" drag style="width: 100%">
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>请上传已通过审批的报价单。</span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as OrderApi from '@/api/order'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { InfoFilled } from '@element-plus/icons-vue'

defineOptions({ name: 'TestForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  projectName: '',
  deliverables: '',
  orderId: null,
  orderContent: null,
  demand: '',
  quote: 0,
  payMethod: null,
  expectedDate: '',
  file: []
})
const formRules = reactive({
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  deliverables: [{ required: true, message: '交付物不能为空', trigger: 'blur' }],
  quote: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
  payMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '报价单不能为空', trigger: 'blur' }],
  expectedDate: [{ required: true, message: '交付时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 日期选择器禁用当前日期之前
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7// - 8.64e7是今天可以选
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    projectName: '',
    deliverables: '',
    orderId: null,
    orderContent: null,
    demand: '',
    quote: 0,
    payMethod: null,
    expectedDate: '',
    file: []
  }
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  file.value = []
}

/** 打开弹窗 */
const open = async (row) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑报价'
  resetForm()
  // 修改时，设置数据
  if (row.orderId) {
    formLoading.value = true
    try {
      formData.value = {
        orderId: row.orderId,
        orderContent: row.orderContent,
        demand: row.demand,
        quote: row.quote,
        payMethod: row.payMethod,
        expectedDate: row.expectedDate,
        file: row.quoteFile,
        projectName: row.projectName,
        deliverables: row.deliverables,
      }
      if (row.quoteFile) {
        file.value = JSON.parse(row.quoteFile)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const uploadRef = ref()
const file = ref([])
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/testManager/testForm/verify'
const uploadHeaders = ref() // 上传 Header 头
const beforeUpload = (file) => {
  if (file.size / 1024 / 1024 > 16) {
    message.error('上传文件大小不能大于16M');
    return false;
  }
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
/** 文件上传成功 */
const submitFormSuccess = (response: any) => {
  if (response.code !== 200) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
}

const handleChange = (uploadFile) => {
  formData.value.file = uploadFile
}

const handleRemove = () => {
  formData.value.file = []
}

const handlePreview = async (file) => {
  window.open(file.url)
}

const submitDisabled = ref(false)
/** 提交 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  submitDisabled.value = true
  uploadRef.value!.submit()
  try {
    const data = new FormData()
    const params = {
      ...formData.value
    }
    if (file.value.length) {
      file.value.forEach((item) => {
        if (item.raw) {
          data.append(`file`, item.raw)
        } else {
          data.append(`file`, new Blob([item.url], { type: '' }))
        }
      })
    } else {
      data.append('file', new Blob([], { type: '' }))
    }
    data.append('quoteSaveReqVO', new Blob([JSON.stringify(params)], { type: 'application/json' }))
    await OrderApi.editQuoteInfo(data)
    message.success('报价编辑成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    submitDisabled.value = false
  }
}
</script>

<style scoped lang="scss">
.test-form {
  padding-top: 3%;
}

.test-tree {
  width: 100%;
  display: flex;
}

.test-form-footer {
  display: flex;
  justify-content: center;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.num {
  color: var(--el-color-primary);
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // margin: 0 0px 0 0px;
  font-size: 12px;
}

.disabled {
  width: 100%;
  cursor: not-allowed;
}

.tree-node {
  display: flex;
  align-items: center;
}

:deep(.el-tree) {
  padding: 10px 10px 10px 0;

  .el-tree-node {
    .el-tree-node__content {
      // display: flex;
      // justify-content: space-between;
    }

    i.el-tree-node__expand-icon {
      svg {
        display: none;
      }
    }

    i.el-tree-node__expand-icon {
      display: none;
    }
  }

  .el-tree-node.is-current {
    .el-tree-node__content {
      small {
        color: #5e7ce0;
      }
    }

    .el-tree-node__children {
      small {
        color: unset;
      }
    }
  }

  /* ^ 树节点 */
  .el-tree-node {
    position: relative;
    width: auto;
    padding-left: 13px;

    &::before {
      width: 1px;
      height: 100%;
      content: '';
      position: absolute;
      top: -38px;
      bottom: 0;
      left: 0;
      right: auto;
      border-width: 1px;
      border-left: 1px solid #b8b9bb;
    }

    &::after {
      width: 13px;
      height: 13px;
      content: '';
      position: absolute;
      z-index: 0;
      left: 0;
      right: auto;
      top: 12px;
      bottom: auto;
      border-width: 1px;
      border-top: 1px solid #b8b9bb;
    }

    .el-tree-node__content {
      position: relative;
      z-index: 1;
      padding-left: 0 !important;
    }

    .el-tree-node__children {
      padding-left: 12px;
    }

    &:last-child::before {
      height: 50px;
    }
  }

  >.el-tree-node {
    padding-left: 0;

    &::before {
      border-left: none;
    }

    &::after {
      border-top: none;
    }
  }
}

:deep(.disabled-tree) {
  .el-checkbox {
    pointer-events: none;
    cursor: not-allowed;
  }

  .el-checkbox__input {
    .el-checkbox__inner {
      // 禁用的样式
      background-color: rgb(237, 242, 252);
      border-color: rgb(217, 217, 217);
    }

    &.is-checked {

      // 勾选状态下的样式,不加的话禁用时勾选是灰色的
      .el-checkbox__inner {
        background-color: rgb(49, 56, 69);
        border-color: rgb(49, 56, 69);
      }
    }
  }
}
</style>
